// pages/judge/score/score.js
const app = getApp();

Page({
  data: {
    stats: {
      total: 0,
      reviewed: 0,
      pending: 0,
      avgScore: 0,
    },
    statsTime: "",
    majorList: [
      "全部",
      "计算机科学与技术",
      "软件工程",
      "数据科学与大数据技术",
      "人工智能",
    ],
    gradeList: ["全部", "2021级", "2022级", "2023级", "2024级"],
    statusList: ["全部", "已完成", "待评审", "草稿"],
    majorIndex: 0,
    gradeIndex: 0,
    statusIndex: 0,
    scoreList: [],
  },

  onLoad() {
    this.loadStats();
    this.loadScoreList();
  },

  onShow() {
    this.loadStats();
    this.loadScoreList();
  },

  loadStats() {
    this.setData({
      statsTime: this.formatTime(new Date()),
    });

    // 模拟统计数据
    this.setData({
      stats: {
        total: 156,
        reviewed: 89,
        pending: 67,
        avgScore: 85.6,
      },
    });
  },

  formatTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  async loadScoreList() {
    try {
      const result = await this.getScoreList();
      if (result.success) {
        this.setData({ scoreList: result.data });
      }
    } catch (error) {
      console.error("加载评分列表失败:", error);
    }
  },

  getScoreList() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${app.globalData.baseUrl}/judge/scores`,
        method: "GET",
        header: {
          Authorization: `Bearer ${wx.getStorageSync("token")}`,
        },
        data: {
          major: this.data.majorList[this.data.majorIndex],
          grade: this.data.gradeList[this.data.gradeIndex],
          status: this.data.statusList[this.data.statusIndex],
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve({ success: true, data: res.data });
          } else {
            resolve({ success: false, data: [] });
          }
        },
        fail: reject,
      });
    });
  },

  onMajorChange(e) {
    const index = e.detail.value;
    this.setData({ majorIndex: index });
    this.loadScoreList();
  },

  onGradeChange(e) {
    const index = e.detail.value;
    this.setData({ gradeIndex: index });
    this.loadScoreList();
  },

  onStatusChange(e) {
    const index = e.detail.value;
    this.setData({ statusIndex: index });
    this.loadScoreList();
  },

  resetFilter() {
    this.setData({
      majorIndex: 0,
      gradeIndex: 0,
      statusIndex: 0,
    });
    this.loadScoreList();
  },

  viewScore(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/judge/review/review?id=${id}`,
    });
  },

  editScore(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/judge/review/review?id=${id}&edit=true`,
    });
  },

  deleteScore(e) {
    const id = e.currentTarget.dataset.id;

    wx.showModal({
      title: "确认删除",
      content: "删除后无法恢复，确认删除这个评分记录吗？",
      success: (res) => {
        if (res.confirm) {
          this.doDeleteScore(id);
        }
      },
    });
  },

  async doDeleteScore(id) {
    wx.showLoading({ title: "删除中..." });

    try {
      const result = await this.deleteScoreRequest(id);
      if (result.success) {
        wx.showToast({
          title: "删除成功",
          icon: "success",
        });
        this.loadScoreList();
      } else {
        wx.showToast({
          title: result.message || "删除失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("删除评分失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "error",
      });
    } finally {
      wx.hideLoading();
    }
  },

  deleteScoreRequest(id) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${app.globalData.baseUrl}/judge/scores/delete`,
        method: "DELETE",
        header: {
          Authorization: `Bearer ${wx.getStorageSync("token")}`,
          "Content-Type": "application/json",
        },
        data: { id },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve({ success: true, data: res.data });
          } else {
            resolve({ success: false, message: res.data.message });
          }
        },
        fail: reject,
      });
    });
  },

  batchReview() {
    wx.navigateTo({
      url: "/pages/judge/batch/batch",
    });
  },

  exportScores() {
    wx.showLoading({ title: "导出中..." });

    // 模拟导出过程
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: "导出成功",
        icon: "success",
      });
    }, 2000);
  },
});
